package com.fruit.service.order.impl;


import java.io.PrintWriter;
import java.io.StringWriter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fruit.mapper.order.OrderMapper;
import com.fruit.pojo.order.OrderException;
import com.fruit.pojo.order.TransactionException;
import com.fruit.util.DateUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class OrderLogService{


	
	@Autowired
	private OrderMapper orderMapper;	
	
	public void newSaveExceptionTransaction(String tradeId,String serviceName,String serviceState,String transactionCode,int userId, String code, String message){
		try{
		log.info("[{}]-【交易流水异常日志】-【交易流水号：{}】",tradeId, transactionCode);
		TransactionException te = new TransactionException();
		te.setTradeId(tradeId);
		te.setServiceName(serviceName);
		te.setTransactionCode(transactionCode);
		te.setUserId(userId);
		JSONObject paJson=new JSONObject();
		paJson.put("code", transactionCode);
		te.setInputParams(paJson.toString());
		te.setServiceState(serviceState);
		te.setErrorCode(code);
		te.setErrorMessage(message);
		te.setQueryTime(DateUtil.getTime());
		orderMapper.saveExceptionTransaction(te);
		log.info("[{}]-【交易流水异常日志】-【成功】",tradeId);
		}catch(Exception e){
			log.error("[{}]-【交易流水异常日志】-【异常】------【{}】",tradeId,getStackTraceAsString(e));
		}
		log.info("[{}]-【交易流水异常日志】-【结束】",tradeId);
		
	}
	
	public void newSaveExceptionOrder(String tradeId,String serviceName,String serviceState,String orderCode,int userId, String code, String message){
		try{
		log.info("[{}]-【订单异常日志】-【订单号：{}】",tradeId, orderCode);
		OrderException oe = new OrderException();
		oe.setTradeId(tradeId);
		oe.setServiceName(serviceName);
		oe.setOrderCode(orderCode);
		oe.setUserId(userId);
		JSONObject paJson=new JSONObject();
		paJson.put("code", orderCode);
		oe.setInputParams(paJson.toString());
		oe.setServiceState(serviceState);
		oe.setErrorCode(code);
		oe.setErrorMessage(message);
		oe.setQueryTime(DateUtil.getTime());
		orderMapper.saveExceptionOrder(oe);
		log.info("[{}]-【订单异常日志】-【成功】",tradeId);
		}catch(Exception e){
			log.error("[{}]-【订单异常日志】-【异常】------【{}】",tradeId,getStackTraceAsString(e));
		}
		log.info("[{}]-【订单异常日志】-【结束】",tradeId);
		
	}

	public String getStackTraceAsString(Throwable ex) {
		StringWriter stringWriter = new StringWriter();
		ex.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}
	
}
